﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.Web;
using System.Net;

namespace FacebookTestUserManager
{
    public partial class FriendSettingWindow : Window
    {
        public string AccessToken { set; get; }
        public string AppId { set; get; }
        public string UserId { set; get; }
        public string UserAccessToken { set; get; }
        public List<TestUser> Friends { set; get; }

        public FriendSettingWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(FriendSettingWindow_Loaded);
        }

        void FriendSettingWindow_Loaded(object sender, RoutedEventArgs e)
        {
            string fql = string.Format("SELECT uid2 FROM friend WHERE uid1=me()");
            var helper = new FacebookHelper(this.AppId, this.AccessToken);
            dynamic results = helper.Query(fql, this.UserAccessToken);
            var friendsIdList = new List<string>();
            foreach (var f in results)
                friendsIdList.Add(f["uid2"]);

            for (int i = 0; i < this.Friends.Count; i++)
            {
                this.Friends[i].isFriend = friendsIdList.Contains(this.Friends[i].id);
            }

            this.dataGrid1.DataContext = Friends;
        }

        private void friendsSetting_Click(object sender, RoutedEventArgs e)
        {
            var idAndToken = (sender as Hyperlink).DataContext as string;
            var splited = idAndToken.Split(',');

            var friendId = splited[0];
            var friendAccessToken = splited[1];

            var helper = new FacebookHelper(this.AppId, this.AccessToken);
            helper.Friends(this.UserId, friendId, this.UserAccessToken);
            helper.Friends(friendId, this.UserId, friendAccessToken);

            this.Close();
            
        }

        private void connectAllFriends_Click(object sender, RoutedEventArgs e)
        {
            foreach (var friend in this.dataGrid1.DataContext as List<TestUser>)
            {
                if (friend.isFriend)
                    continue;

                var helper = new FacebookHelper(this.AppId, this.AccessToken);
                helper.Friends(this.UserId, friend.id, this.UserAccessToken);
                helper.Friends(friend.id, this.UserId, friend.access_token);

                this.Close();
            }
        }
    }
}
